import { get } from "../cache";
import jwt from 'jsonwebtoken';

export async function  decodedToken(HTTPAuthorization, deviceUUID){
    //验证token

    const authArr = HTTPAuthorization.split(" ")
    const token  = authArr[1];

    //开始使用jwt验证token

    const secret = await get(deviceUUID);

    const decoded = jwt.verify(token, secret);
    
}

export async function authenticate(decoded, deviceUUID){
    const userCache = await get(deviceUUID+"_plant");
    const userInfo = JSON.parse(userCache);
    if(decoded.id !== userInfo.id){
        return false
    }
    if(decoded.username !== userInfo.username){
        return false
    }
    if(decoded.password !== userInfo.password){
        return false;
    }
    return userInfo;
}


export async function authorize(userInfo, source){
    const sourceName = source.name;
    const sourceId = source.id;
    if(sourceName){
        
    }
}





export default {
    APIError: function (code, message) {
        this.code = code || 'internal:unknown_error';
        this.message = message || '';
    },
    restify: (pathPrefix) => {
        pathPrefix = pathPrefix || '/api/';
        return async (ctx, next) => {
            ctx.set('Access-Control-Allow-Origin', '*');
            ctx.set('Access-Control-Expose-Headers', 'Content-Range');
            ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
            ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
            if (ctx.request.path.startsWith(pathPrefix)) {
                // 绑定rest()方法:
                
                ctx.rest = (data) => {
                    ctx.response.type = 'application/json';
                    ctx.response.body = data;
                }
                try {
                    await next();
                } catch (e) {
                    // 返回错误:
                    console.error(e);
                    ctx.response.status = 400;
                    ctx.response.type = 'application/json';
                    ctx.response.body = {
                        code: e.code || 'internal:unknown_error',
                        message: e.message || ''
                    };
                }
            } else {
                await next();
            }
        };
    }
};